package com.yiquan.video.service;

/**
 * @author Tyrone
 * @date 2022/3/22 14:13
 */

import com.github.pagehelper.PageHelper;
import com.yiquan.video.mapper.TagMapper;
import com.yiquan.video.pojo.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 * 标签服务
 */
@Service
@Slf4j
public class TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String ViDEO_MODULE_ID = "VIDEO_MODULE_ID";

    /**
     * 获取用户id (20000000-29999999)
     *
     * @return
     */
    public Long getUniqueId() {
        redisTemplate.opsForValue().setIfAbsent(ViDEO_MODULE_ID, 20000000L);
        Long temporaryUserId = redisTemplate.opsForValue().increment(ViDEO_MODULE_ID);
        return temporaryUserId;
    }


    /**
     * 根据标签引用次数倒叙返回 （支持分页）
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<Tag> listTagByRefTimesAsPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Tag> tags = tagMapper.listByRefTimes();
        return tags;
    }

    /**
     * 新增tag
     * @param tag
     */
    public void saveTag(Tag tag) {
        tag.setTagId(getUniqueId());
        tag.setTagStatus(Tag.STATUS_DELETE);
        tag.setCreateDate(new Date());
        tag.setTagRefTimes(1);
    }

    /**
     * 更新tag
     * @param tag
     */
    public void updateTag(Tag tag) {
        Assert.notNull(tag.getTagId(),"更新tag时不允许tagId为空");
        tagMapper.updateByTagIdSelective(tag);
    }
}
